<template>
  <div class="product-list">
    <div class="title">产品列表</div>
    <div>
      <el-form ref="form" :inline="true" class="search-form">
        <el-col :span="24">
          <el-form-item label="产品名称">
            <el-input v-model="formSearch.name" placeholder="请输入产品名称" clearable />
          </el-form-item>
          <el-form-item label="产品ID">
            <el-input v-model="formSearch.productId" placeholder="请输入产品ID" clearable />
          </el-form-item>
          <el-form-item label="产品型号">
            <el-input v-model="formSearch.productModel" placeholder="请输入产品型号" clearable />
          </el-form-item>
          <el-form-item label="产品类型">
            <el-cascader
              v-model="categoryValue"
              :options="categoryList"
              placeholder="请选择产品类型"
              popper-class="cascader-custom-popper"
              clearable
              @change="handleCategory"></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="19">
          <el-form-item label="开发状态">
            <el-select v-model="formSearch.developStatus" clearable>
              <el-option
                v-for="item in developStatusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="设备类型">
            <el-select v-model="formSearch.deviceType" clearable>
              <el-option
                v-for="item in deviceTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="产品说明">
            <el-input v-model="formSearch.description" placeholder="请输入产品说明" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <div class="button-container">
            <el-button
              type="primary"
              size="14"
              @click="queryList('search')">查询</el-button>
            <el-button
              type="primary"
              size="14"
              @click="resetSearch">重置</el-button>
            <el-button
              :disabled="rolesCode !== 'CUSTOM_ADMIN' && rolesCode !== 'PRODUCT'"
              type="primary"
              size="14"
              @click="createProduct">产品创建</el-button>
          </div>
        </el-col>
      </el-form>
    </div>
    <el-table
      v-loading="loading"
      :data="tableData"
      style="width: 100%"
      size="medium"
      :header-cell-style="{ background: '#F5F6F7' }">
      <el-table-column label="产品信息" width="300">
        <template slot-scope="scope">
          <div class="product-info">
            <div class="info-img"><img :src="scope.row.icon || productTypeImg" alt="" /></div>
            <div class="column-content">
              <div class="description">{{ scope.row.name || "-" }}</div>
              <div class="details">{{ scope.row.categoryName || "-" }}</div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="设备类型">
        <template slot-scope="scope">
          {{ deviceType[scope.row.deviceType] || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="产品型号">
        <template slot-scope="scope">
          {{ scope.row.productModel || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="产品ID">
        <template slot-scope="scope">
          {{ scope.row.productId || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="通讯协议" show-overflow-tooltip>
        <template slot-scope="scope">
          <div>{{ scope.row.communicationProtocol || "-" }}</div>
        </template>
      </el-table-column>
      <el-table-column label="配网方式" show-overflow-tooltip>
        <template slot-scope="scope">
          <div>{{ scope.row.networkDistributeMode || "-" }}</div>
        </template>
      </el-table-column>
      <el-table-column label="开发状态" width="100">
        <!-- <template #header>
          <el-popover
            ref="statusPopover"
            placement="bottom"
            width="150"
            trigger="click"
            popper-class="custom-popover">
            <div slot="reference">
              <span class="search-title">开发状态</span>
              <i class="iconfont icon-biaogeshaixuan"></i>
            </div>
            <el-checkbox-group v-model="selectValue" class="status-group">
              <el-checkbox
                v-for="item in selectOptions"
                :key="item.value"
                :value="item.value"
                :label="item.value"
                class="status-checkbox">
                <div>{{ item.label }}</div>
              </el-checkbox>
            </el-checkbox-group>
            <div class="status-btn-box">
              <el-button size="mini" type="primary" class="btn" @click="filterStatus">确定</el-button>
            </div>
          </el-popover>
        </template> -->
        <template slot-scope="scope">
          {{ getStatusText(scope.row.developStatus) }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" sortable min-width="100">
        <template slot-scope="scope">
          {{ scope.row.createTime || "-" }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="最后更新时间" sortable min-width="120">
        <template slot-scope="scope">
          {{ scope.row.updateTime || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="产品说明" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.description || "-" }}
        </template>
      </el-table-column>
      <el-table-column v-if="envVar" label="同步状态" width="120">
        <template slot-scope="scope">
          <el-button type="text" size="operate" @click="syncData(scope.row.productId, 'test')">测试</el-button>
          <el-button type="text" size="operate" @click="syncData(scope.row.productId, 'prod')">生产</el-button>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="120">
        <template slot-scope="scope">
          <el-button type="text" size="operate" @click="jumpDetails(scope.row)">详情</el-button>
          <el-button
            v-if="!scope.row.developStatus"
            type="text"
            size="operate"
            :disabled="rolesCode !== 'CUSTOM_ADMIN'"
            @click="handleDelete(scope.row.productId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :page-sizes="[10, 20, 50]"
      :current-page="currentPage"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange">
    </el-pagination>
  </div>
</template>

<script>
import { productList, detele, syncInfo } from '@/api/product/product-list'
import { deviceCategories } from '@/api/product/create-product'
import { mapGetters } from 'vuex'
import { productTypeImg } from '../../../../public/images/product_type.png'
export default {
  name: "ProductList",
  data() {
    return {
      productTypeImg: productTypeImg,
      formSearch: {
        productId: "", // 产品ID
        name: "", // 产品名称
        productModel: "", // 产品型号
        developStatus: "", // 开发状态
        deviceType: "", // 设备类型
        description: "" // 产品说明
      },
      productIdOrName: "", // 产品id或名称
      description: "", // 产品说明
      tableData: [], // 列表数据
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页条数
      total: 0, // 列表数据总条数
      developStatusOptions: [ // 列表开发状态
        {
          value: '',
          label: '全部'
        },
        {
          value: '0',
          label: '开发中'
        },
        {
          value: '1',
          label: '开发完成'
        }
      ],
      deviceTypeOptions: [ // 设备类型
        {
          value: '',
          label: '全部'
        },
        {
          value: 'device',
          label: '普通设备'
        },
        {
          value: 'childrenDevice',
          label: '网关子设备'
        },
        {
          value: 'gateway',
          label: '网关设备'
        }
      ],
      // selectValue: [], // 列表开发状态选中的数据
      categoryValue: [], // 级联筛选产品列表
      categoryFilterValue: '', // 接口传参产品大类+小类拼接
      categoryList: [], // 产品列表
      rawData: [], // 放原始JSON数据
      loading: true
    }
  },
  computed: {
    ...mapGetters(['rolesCode']),
    statusMapping() { // 开发状态
      return {
        '': '全部',
        0: '开发中',
        1: '开发完成'
      }
    },
    deviceType() { // 设备类型
      return {
        'device': '普通设备',
        'childrenDevice': '网关子设备',
        'gateway': '网关设备'
      }
    },
    envVar() {
      return window.location.hostname === '10.111.115.183'
    }
  },
  created() {
    this.currentPage = sessionStorage.getItem('currentPage') ? Number(sessionStorage.getItem('currentPage')) : 1
    this.formSearch.productId = sessionStorage.getItem('productId') || ''
    this.formSearch.name = sessionStorage.getItem('name') || ''
    this.formSearch.productModel = sessionStorage.getItem('productModel') || ''
    this.formSearch.developStatus = sessionStorage.getItem('developStatus') || ''
    this.formSearch.deviceType = sessionStorage.getItem('deviceType') || ''
    this.formSearch.description = sessionStorage.getItem('description') || ''
    const storedCategory = sessionStorage.getItem('categoryValue') || ''
    if (!storedCategory) {
      this.categoryValue = []
      this.categoryFilterValue = ''
    } else {
      this.categoryValue = storedCategory.split(",")
      this.categoryFilterValue = this.categoryValue[this.categoryValue.length - 1]
    }

    sessionStorage.removeItem('currentPage')
    sessionStorage.removeItem('productId')
    sessionStorage.removeItem('name')
    sessionStorage.removeItem('productModel')
    sessionStorage.removeItem('developStatus')
    sessionStorage.removeItem('deviceType')
    sessionStorage.removeItem('description')
    sessionStorage.removeItem('categoryValue')
    this.queryList()
    this.queryCategory()
  },
  methods: {
    getStatusText(status) {
      return this.statusMapping[status] || ''
    },
    // 跳转创建产品
    createProduct() {
      this.$router.push({ path: "/product/create-product/index" })
      sessionStorage.setItem('currentPage', this.currentPage)
      sessionStorage.setItem('productId', this.formSearch.productId)
      sessionStorage.setItem('name', this.formSearch.name)
      sessionStorage.setItem('productModel', this.formSearch.productModel)
      sessionStorage.setItem('developStatus', this.formSearch.developStatus)
      sessionStorage.setItem('deviceType', this.formSearch.deviceType)
      sessionStorage.setItem('description', this.formSearch.description)
      sessionStorage.setItem('categoryValue', this.categoryValue)
    },
    // 查询产品品类
    queryCategory() {
      deviceCategories().then(res => {
        this.rawData = res.data.data.categories
        this.categoryList = this.rawData.map(std => ({
          label: std.standardCategory,
          value: std.standardCategory,
          children: std.primaryClassification.map(primary => ({
            label: primary.category,
            value: primary.category,
            children: primary.secondClassification.map(second => ({
              label: second.name,
              value: second.categoryCode
            }))
          }))
        }))
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    /**
     * 查询产品列表
     * @param current 当前页码
     * @param size 每页条数
     * @param developStatus 开发状态
     * @param category 产品类型
     * @param productId 产品ID
     * @param name 产品名称
     */
    queryList(condition) {
      this.currentPage = condition === 'search' ? 1 : this.currentPage
      this.loading = true
      const params = {
        current: this.currentPage,
        size: this.pageSize,
        categoryCode: this.categoryFilterValue,
        ...this.formSearch
      }
      productList(params).then(res => {
        this.tableData = res.data.data.records
        this.total = res.data.data.total
      }).catch(err => {
        this.$message.error(err.message)
      }).finally(() => {
        this.loading = false
      })
    },
    /**
     * 删除产品
     * @param productId 产品id
     */
    handleDelete(productId) {
      const params = {
        productId
      }
      this.$confirm('产品删除后不可恢复，请谨慎操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        detele(params).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.queryList()
        }).catch(err => {
          this.$message.error(err.message)
        })
      }).catch(err => {})
    },
    // 选择产品类型
    handleCategory(value) {
      this.categoryFilterValue = value[value.length - 1]
      this.queryList('search')
    },
    // 产品详情
    jumpDetails(row) {
      this.$router.push({
        path: "/product/product-details/index",
        query: {
          productId: row.productId,
          developStatus: row.developStatus,
          productName: row.name
        }
      })
      sessionStorage.setItem('currentPage', this.currentPage)
      sessionStorage.setItem('productId', this.formSearch.productId)
      sessionStorage.setItem('name', this.formSearch.name)
      sessionStorage.setItem('productModel', this.formSearch.productModel)
      sessionStorage.setItem('developStatus', this.formSearch.developStatus)
      sessionStorage.setItem('deviceType', this.formSearch.deviceType)
      sessionStorage.setItem('description', this.formSearch.description)
      sessionStorage.setItem('categoryValue', this.categoryValue)
    },
    // 重置查询条件
    resetSearch() {
      this.formSearch = {
        productId: "", // 产品ID
        name: "", // 产品名称
        productModel: "", // 产品型号
        developStatus: "", // 开发状态
        deviceType: "", // 设备类型
        description: "" // 产品说明
      }
      this.categoryValue = []
      this.categoryFilterValue = ''
      // this.selectValue = []
      this.queryList()
    },
    // 每页条数改变时触发
    handleSizeChange(val) {
      this.pageSize = val
      this.queryList()
    },
    // 当前页变时触发
    handleCurrentChange(val) {
      this.currentPage = val
      this.queryList()
    },
    // 列表开发状态查询
    filterStatus() {
      this.queryList()
      this.$refs.statusPopover.doClose()
    },
    isTooltipVisible(content) {
      // 设置一个阈值，比如超过 15 个字符才显示
      const threshold = 11
      return content.length > threshold
    },
    // 同步不同环境数据
    syncData(productId, env) {
      const params = {
        productIdList: [productId],
        env
      }
      this.$confirm('确定同步数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        syncInfo(params).then(res => {
          this.$message({
            type: 'success',
            message: '同步数据成功!'
          })
        }).catch(err => {
          this.$message.error(err.message)
        })
      }).catch(err => {})
    }
  }
}
</script>

<style lang="scss" scoped>
.product-list {
  height: 100%;

  .title {
    font-size: 18px;
    font-weight: 600;
    color: #252525;
    margin-bottom: 21px;
  }

  .search-icon {
    cursor: pointer;
  }

  .button-container {
    float: right;
  }

  .product-info {
    display: flex;
    align-items: center;

    .info-img {
      width: 48px;
      height: 48px;
      margin-right: 16px;

      img {
        width: 48px;
        height: 48px;
      }
    }

    .details {
      color: #7A7B80;
      font-size: 12px;
    }
  }
}

.iconfont {
  margin-left: 2px;
  cursor: pointer;
}

.status-group {
  padding: 0 12px;

  .status-checkbox {
    display: block;
    height: 40px;
    line-height: 40px;
  }
}

.status-btn-box {
  text-align: center;
  border-top: 1px solid #E5E6E9;
  margin-top: 10px;

  .btn {
    margin-top: 10px;
  }
}

::v-deep .el-table__fixed-right-patch {
  background: #F5F6F7;
}

::v-deep .el-input-group__append {
  background: transparent;
}
</style>
<style>
.custom-popover {
  min-width: 127px !important;
  padding: 12px 0;
}

.cascader-custom-popper,
.cascader-custom-popper .el-cascader-menu,
.cascader-custom-popper .el-cascader-menu__wrap {
  height: 300px;
}
</style>
